package org.spring.demo;

import org.spring.demo.service.OrderService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author yangjian
 */
@ComponentScan("org.spring.demo")
@EnableAspectJAutoProxy // enable aop
@EnableTransactionManagement
@Configuration // 增加这个注解之后，jDBCTemplate 和 transactionManager 拿到的才会是同一个 dataSource
public class AppConfig1 { // AppConfig 代理对象

	// register a bean with the name 'orderService', the default name of bean is the method name
	// we can use the name property override it
	@Bean(name = "orderService")
	public OrderService orderService()
	{
		return new OrderService();
	}

	@Bean
	public JdbcTemplate jdbcTemplate()
	{
		return new JdbcTemplate(dataSource());
	}


	@Bean
	public PlatformTransactionManager transactionManager()
	{
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource());
		return transactionManager;
	}

	@Bean
	public DataSource dataSource() {
		String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
		String username = "root";
		String password = "123456";
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		return dataSource;
	}
}
